<template>
  <div class="mod-order-order">
      <el-form :inline="true"
              :model="dataForm"
              @keyup.enter.native="getDataList(this.page)">
        <el-form-item>
          <el-input v-model="dataForm.orderNumber"
                    placeholder="订单编号"
                    clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker v-model="dateRange"
                          type="datetimerange"
                          range-separator="至"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <template>
          <el-select v-model="searchOrderState" placeholder="请选择订单状态" >
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="item.label"
              :value="index">
            </el-option>
          </el-select>
          <!-- {{searchOrderState}} -->
          </template>
          <template v-if="userId == 1">
            <el-select v-model="queryShopId"
                      clearable
                      filterable  
                      placeholder="请选择商铺">
              <el-option v-for="item in shopNameAndId"
                        :key="item.shopId"
                        :label="item.shopName"
                        :value="item.shopId">
              </el-option>
            </el-select>
          </template>
          
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                    icon="el-icon-search"
                    size="small"
                    @click.stop="getDataList({total: 0,currentPage: 1,pageSize: 10})">查询</el-button>
          <el-button v-if="isAuth('order:order:waitingConsignmentExcel')"
                    @click="getWaitingConsignmentExcel"
                    type="primary"
                    size="small">导出待发货订单</el-button>
<!--          <el-button v-if="isAuth('order:order:waitingConsignmentExcel')"
                    @click="showConsignmentInfo()"
                    type="primary"
                    size="small">导出待发货订单</el-button> -->
<!--          <el-button v-if="isAuth('order:order:soldExcel')"
                    @click="getSoldExcel()"
                    type="primary"
                    size="small">导出销售记录</el-button> -->
        </el-form-item>
      </el-form>

    <devy-add v-if="devyVisible" ref="devyAdd"  @refreshDataList="getDataList"></devy-add>



    <div class="main">
      <div class="content" style="font-size:14px">
        <div class="tit">
          <el-row style="width:100%">
            <el-col :span="2"><div class="item">来源店铺</div></el-col>
            <el-col :span="6"><div class="item product">商品</div></el-col>
            <el-col :span="3"><div class="item">成交单价/购买数量</div></el-col>
            <el-col :span="4"><div class="item">收货人信息</div></el-col>
            <el-col :span="2"><div class="item">订单类型</div></el-col>
            <el-col :span="4"><div class="item">订单状态</div></el-col>
            <el-col :span="3"><div class="item">操作</div></el-col>
          </el-row>
        </div>

        <div class="prod"
             v-for="order in dataList"
             :key="order.orderId">
          <div class="prod-tit">
            <span>订单编号：{{order.orderNumber}}</span>
            <span>下单时间：{{order.createTime}}</span>
            <!-- <span v-if="order.userAddrOrder.receiver">买家：{{order.userAddrOrder.receiver}}</span>
            <span >联系电话：{{order.userAddrOrder.mobile}}</span> -->
						<span class="dvyFlowid" v-if="order.dvyFlowId">物流单号： {{order.dvyFlowId}}</span>
          </div>
          <div class="prod-cont">
            <el-row style="width:100%">
              <el-col :span='2' style="height:100%;">
                <div class="item">
                  {{order.shopDetail.shopName}}
                </div>
              </el-col>
              <el-col :span="6">
                <div class="prod-item">
                  <div class="items name"
                       v-for="orderItem in order.orderItems"
                       :key="orderItem.orderItemId">
                    <div class="prod-image">
                      <img :src="resourcesUrl + orderItem.pic"
                           style="height:100px;width: 100px;">
                    </div>
                    <div class="prod-name-price">
                      <div class="prod-name">
                        <span>{{orderItem.prodName}}</span>
                        <!-- <span>{{orderItem.prodName}}</span> -->
                        <!-- <span class="prod-info">{{orderItem.skuName}}</span> -->
                      </div>
                      <div class="prod-price">
                        <span>￥{{orderItem.price}}</span>
                        <el-tag type="danger" size="mini" v-if="order.tjr" class="spreadOrder">推</el-tag>
                        <el-tag type="success" size="mini" v-if="order.ptstatus == 1" class="ptOrder">拼单成功</el-tag>
                        <el-tag type="primary" size="mini" v-if="order.ptstatus == 0" class="ptOrder">待拼团</el-tag>
                        <el-tag type="danger" size="mini" v-if="order.ptstatus == 2" class="ptOrder">拼团失败</el-tag>
                      </div>
                      <div class="prod-count">
                        <span>x{{orderItem.prodCount}}</span>
                      </div>
                      <div class="ptstatus">
												
											</div>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col :span="3"
                      style="height: 100%;">
                <div class="item">
                  <div>
                    <span class="totalprice">￥{{order.actualTotal}}</span>
                    <span v-if="order.freightAmount">（含运费：￥{{order.freightAmount}}）</span>
                    <span>共{{order.productNums}}件</span>
                  </div>
                </div>
              </el-col>
              <el-col :span="4"
                      style="height: 100%;">
                <div class="item" style="padding: 20px 0;flex-direction: column;justify-content: space-around;align-items: flex-start;padding:15px;">
                  <div v-if="order.userAddrOrder.receiver">
                    收货人： {{order.userAddrOrder.receiver}}
                  </div>
                  <div v-if="order.userAddrOrder.mobile">
                    电话： {{order.userAddrOrder.mobile}}
                  </div>
                  <div v-if="order.userAddrOrder.province">
                    收货地址：{{order.userAddrOrder.province}}{{order.userAddrOrder.city}}{{order.userAddrOrder.area}}{{order.userAddrOrder.street}}{{order.userAddrOrder.addr}}
                  </div>
                </div>
              </el-col>

              <el-col :span="2" style="height: 100%;">
                <div class="item">
                  <span v-if="order.distributionType == 1">自提</span>
                  <span v-else>非自提</span>
                </div>
              </el-col>
              <el-col :span="4"
                      style="height: 100%;">
                <div class="item">
                  <div v-if="order.orderState===0&&order.refundState == 3">
                    退款审核失败
                  </div>
                  <div v-else-if="order.orderState===0&&order.status === 1"
                        size="small"
                        type="danger">等待买家付款</div>
                  <template v-else-if="order.orderState===0&&order.status === 2">
										<div v-if="order.ptglid&&order.ptstatus == 0">待拼团</div>
                    <div v-else-if="userId == 1&& userId !== order.shopId"
                          size="small"
                          type="danger">
                          <span v-if="order.distributionType == 1" >待备货</span>
                          <span v-if="order.distributionType == 2">待美团接单</span>
                          <div v-if="order.distributionType == 0 && order.distributionFlag == 0">
                            <span size="small" style="margin-right:6px;">待配送</span>
                          </div>
                    </div>
                    <div v-else
                          size="small"
                          type="danger">
                          <el-button type="primary" v-if="order.distributionType == 1" @click="goStockUp(order.orderNumber)">去备货</el-button>
                          <span v-if="order.distributionType == 2">待美团接单</span>
                          <div v-if="order.distributionType == 0 && order.distributionFlag == 0">
                            <el-button type="primary" size="small" style="margin-right:6px;" @click="goShip(order.orderNumber)">物流快递</el-button>
                            <el-button type="primary" size="small" @click="goTransfer(order.orderNumber)">商家配送</el-button>
                          </div>
                    </div>
                  </template>
                  <div v-else-if="order.orderState===0&&order.status === 3"
                        size="small" class="blue-font">
                        <span v-if="order.distributionType == 1">等待用户提货</span>
                        <span v-if="order.distributionType == 2">美团配送中</span>
                        <span v-if="order.distributionType == 3">商家配送中</span>
                        <span v-if="order.distributionType == 4">卖家已发货</span>
                  </div>
                  <div v-else-if="order.orderState===0&&order.status === 5" class="green-font">
                        <span v-if="order.distributionType == 1">买家已提货</span>
                        <span v-if="order.distributionType == 2">美团配送完成</span>
                        <span v-if="order.distributionType == 3">商家已送达</span>
                        <span v-if="order.distributionType == 4">买家已收货</span>
                  </div>
                  <div v-else-if="order.orderState===0&&order.status === 6">
                    交易完成
                  </div>
                  <div v-else-if="order.orderState===1&&order.refundState == 0" class="red_font">
                    订单已取消
                  </div>
                  <div v-else-if="order.orderState===1&&order.refundState == 1"  class="red_font">
                    退款待审核
                  </div>
                  <div v-else-if="order.orderState===1&&order.refundState == 2" class="red_font">
                    退款已完成
                  </div>

                  <div v-else
                        size="small">状态异常</div>
                </div>
              </el-col>              
              <el-col :span="3"
                      style="height: 100%;">
                <div class="item">
                  <div class="operate">
                    <!-- <button onclick="">打印订单</button><br> -->

                    <!-- <el-button v-if="isAuth('order:order:update') && userId == 1&& userId !== order.shopId"
                               type="text"  
                               size="small"
                               style="color:#B2B2B2">不可修改</el-button> -->
                    <el-button type="text"
                               size="small"
                               @click="addOrUpdateHandle(order.orderNumber)"><el-tag type="success">查看订单详情</el-tag></el-button>
                    <!-- userid:{{userId}} shopId:{{order.shopId}} -->
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="remark">
            <div class="buyer-remark">
              <span>备注:{{order.remarks}}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-pagination @size-change="sizeChangeHandle"
                   @current-change="currentChangeHandle"
                   :current-page="page.pageIndex"
                   :page-sizes="[10, 20, 50, 100]"
                   :page-size="page.pageSize"
                   :total="page.total"
                   layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible"
                   ref="addOrUpdate"
                   @refreshDataList="getDataList"></add-or-update>
    <consignment-info v-if="consignmentInfoVisible"
                      ref="consignmentInfo"
                      @inputCallback="getWaitingConsignmentExcel"></consignment-info>
  </div>
</template>

<script>
import AddOrUpdate from './orderInfo'
import ConsignmentInfo from './consignment-info'
import DevyAdd from './order-devy'

export default {
  data () {
    return {
      queryShopId :null,
      userId: null,
      dataForm: {},
      dateRange: [],
      shopNameAndId: [],
      devyVisible:false,
      searchOrderState: '', 
      options: [{
        label:'待支付',
        value:{orderState:0, status:1,}
      },
			{
				label:'待发货',
				value:{orderState:0, status:2,}
      },
			{
				label:'待收货/待提货',
				value:{orderState:0, status:3,}
      },
			{
				label:'已收货',
				value:{orderState:0, status:5,}
      },
			{
				label:'已完成',
				value:{orderState:0, status:6,}
      },
			{
				label:'已取消',
				value:{orderState:1, refundState:0,}
      },
			{
				label:'待售后',
				value:{orderState:1, refundState:1,}
      },
			// {
			// 	label:'退款已完成',
			// 	value:{orderState:1, refundState:2,}
   //    },
			// {
			// 	label:'退款失败',
			// 	value:{orderState:0, refundState:3,}
   //    },
			],
			resourcesUrl: window.SITE_CONFIG.resourcesUrl,
			dataList: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      consignmentInfoVisible: false
    }
  },
  components: {
    AddOrUpdate,
    ConsignmentInfo,
    DevyAdd

  },
  activated () {   
    this.getDataList(this.page)   
    this.getShopNameAndId()

      //判断是否为admin 用户 
      this.$http({
        url: this.$http.adornUrl('/sys/user/info'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => { 
        console.log(data);
        this.userId = data.userId
      })
  },
  methods: {
    // 获取数据列表
    getDataList (page, params) {
      console.log(params);
      page = (page === undefined ? this.page : page)
      this.dataListLoading = true
      // console.log(this.options[this.searchOrderState].value);
      this.$http({
        url: this.$http.adornUrl('/order/order/page'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign(
            {
              current: page.currentPage,
              size: page.pageSize,
              // current: page == null ? this.page.currentPage : page.currentPage,
              // size: page == null ? this.page.pageSize : page.pageSize,
              'orderNumber': this.dataForm.orderNumber,
              // 'status': this.searchOrderState.status,
              // 'orderState': this.searchOrderState.orderState,
              // 'refundState': this.searchOrderState.refundState,
              'startTime': this.dateRange === null ? null : this.dateRange[0], // 开始时间
              'endTime': this.dateRange === null ? null : this.dateRange[1], // 结束时间
              'shopId' :this.queryShopId
            },
            this.searchOrderState!==''?this.options[this.searchOrderState].value:{},
            // params
          ), false
        )
      }).then((res) => {
        
        let data = res.data
        this.dataList = data.records
        this.page.total = data.total
        this.dataListLoading = false
        console.log(this.dataList);
      })
    },
    //获取商铺名和id对应列表
    getShopNameAndId(){
      this.$http({
        url:this.$http.adornUrl('/order/order/shopNameAndId'),
        method:'get',
      }).then((res) =>{
        this.shopNameAndId = res.data
      })
    },

    // 备货
    goStockUp (orderNumber) {
      this.$confirm('确定备货完成？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/order/order/delivery`),
          method: 'put',
          data: this.$http.adornData({
            orderNumber
          })
        }).then(({data}) => {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              this.getDataList()
            }
          })
        })
      }).catch(() => {
      });
    },
    
    // 发货
    goShip (orderNumber) {
      this.devyVisible = true
      this.$nextTick(() => {
        this.$refs.devyAdd.init(orderNumber, this.dataForm.dvyId, this.dataForm.dvyFlowId)
      })
    },

    goTransfer(orderNumber){
      this.$confirm('确定选择商家配送并发货？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/order/order/distributionByShop`),
          method: 'post',
          params: this.$http.adornParams({
            orderNumber
          })
        }).then(({data}) => {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              this.getDataList()
            }
          })
        })
      }).catch(() => {
      });      

    },    

    
    // 每页数
    sizeChangeHandle (val) {
      this.page.pageSize = val
      this.page.currentPage = 1
      this.getDataList(this.page)
    },
    // 当前页
    currentChangeHandle (val) {
      this.page.currentPage = val
      this.getDataList(this.page)
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    orderStatus () {

    },
    // 新增 / 修改
    addOrUpdateHandle (val) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(val)
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.orderId
      })
      this.$confirm(`确定进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/prod/spec/${ids}`),
          method: 'delete',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.getDataList(this.page)
            }
          })
        })
      }).catch(() => { })
    },

    showConsignmentInfo () {
      this.consignmentInfoVisible = true
      this.$nextTick(() => {
        this.$refs.consignmentInfo.init()
      })
    },

    getWaitingConsignmentExcel (consignmentInfo) {
      this.$http({
        url: this.$http.adornUrl('/order/order/waitingConsignmentExcel'),
        method: 'get',
        // params: this.$http.adornParams({
        //   'consignmentName': consignmentInfo.consignmentName,
        //   'consignmentMobile': consignmentInfo.consignmentMobile,
        //   'consignmentAddr': consignmentInfo.consignmentAddr,
        //   'startTime': this.dateRange === null ? null : this.dateRange[0], // 开始时间
        //   'endTime': this.dateRange === null ? null : this.dateRange[1] // 结束时间
        // }),
        responseType: 'blob' // 解决文件下载乱码问题
      }).then(({ data }) => {
        var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
        const fileName = '待发货信息整理.xls'
        const elink = document.createElement('a')
        if ('download' in elink) { // 非IE下载
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    getSoldExcel () {
      this.$http({
        url: this.$http.adornUrl('/order/order/soldExcel'),
        method: 'get',
        params: this.$http.adornParams({
          'startTime': this.dateRange === null ? null : this.dateRange[0], // 开始时间
          'endTime': this.dateRange === null ? null : this.dateRange[1] // 结束时间
        }),
        responseType: 'blob' // 解决文件下载乱码问题
      }).then(({ data }) => {
        var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
        const fileName = '销售信息整理.xls'
        const elink = document.createElement('a')
        if ('download' in elink) { // 非IE下载
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.content{
  font-size: 14px;
}
.mod-order-order {
  .tit {
    display: flex;
    height: 45px;
    align-items: center;
  }
  .tit .item {
    padding: 0 10px;
    width: 100%;
    text-align: center;
  }
  .tit .product {
    width: 25%;
  }
  .prod-tit {
    padding: 10px;
    background: #f8f8f9;
    border-left: 1px solid #dddee1;
    border-top: 1px solid #dddee1;
    border-right: 1px solid #dddee1;
		position: relative;
		.dvyFlowid{
			position: absolute;
			right: 20px;
		}
  }
  .prod-tit span {
    margin-right: 15px;
  }

  .prod-cont {
    display: flex;
    border-top: 1px solid #dddee1;
    border-bottom: 1px solid #dddee1;
    border-left: 1px solid #dddee1;
    color: #495060;
  }
  .prod-cont .item {
    display: flex;
    display: -webkit-flex;
    align-items: center;
    justify-content: center;
    
    padding: 10px;
    // width: 10%;
    border-right: 1px solid #dddee1;
    text-align: center;
    height: 100%;
  }
  .red_font{
    color: #C00000;
  }
	.blue-font{
		color: #409EFF;
	}
	.green-font{
		color: #74C557;
	}
  .prod-cont .item span {
    display: block;
  }
  .prod-cont .prod-item {
    // width: 38%;
    display: flex;
    flex-direction: column;
    border-right: 1px solid #dddee1;
    position: relative;
  }
  .prod-name-price{
    width: calc( 100% - 100px);
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
  .prod-name {
    width: 100%;
    text-align: left;
  }
  .prod-price span {
    margin-bottom: 10px;
  }
  .prod-name .prod-info {
    display: block;
    color: #80848f;
    margin-top: 30px;
  }
  .prod-cont .items.name {
    display: flex;
    position: relative;
    padding: 20px;
    // height: 100px;
    border-bottom: 1px solid #dddee1;
  }
  .prod-cont .items.name:last-child {
    border-bottom: none;
  }
  .spreadOrder{
    width: 24px;
    // position: absolute;
    // right: 0;
    // bottom: 0;
  }
  .prod-image {
    margin-right: 20px;
    width: 100px;
    height: 100px;
  }
  .prod-image img {
    width: 100px;
    height: 100px;
  }
  .item span {
    display: block;
    margin-bottom: 10px;
  }
  .item .operate {
    color: #2d8cf0;
  }
  .item .totalprice {
    color: #c00;
  }
  .prod .remark {
    // width: 100%;
    height: 50px;
    line-height: 50px;
    background-color: #e8f7f6;
    border-left: 1px solid #dddee1;
    border-right: 1px solid #dddee1;
    border-bottom: 1px solid #dddee1;
    margin-bottom: 20px;
  }
  .buyer-remark {
    padding: 0 20px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
